package com.imdroid.controller;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import net.orange.architecture.process.ProcessFactory;
import net.orange.architecture.web.Web;

import com.imdroid.IMDroid;
import com.imdroid.logic.IDeviceProcess;
import com.imdroid.modal.Device;

@ManagedBean(name = "login")
@SessionScoped
public class LoginController {
	/**
	 * The login account
	 */
	private String login_no;

	/**
	 * The login password.
	 */
	private String login_pwd;

	/**
	 * @return Returns the login_no.
	 */
	public String getLogin_no() {
		return login_no;
	}

	/**
	 * @param login_no
	 *            The login_no to set.
	 */
	public void setLogin_no(String login_no) {
		this.login_no = login_no;
	}

	/**
	 * @return Returns the login_pwd.
	 */
	public String getLogin_pwd() {
		return login_pwd;
	}

	/**
	 * @param login_pwd
	 *            The login_pwd to set.
	 */
	public void setLogin_pwd(String login_pwd) {
		this.login_pwd = login_pwd;
	}

	/**
	 * Log in
	 * 
	 * @return the JSF tag "login"
	 * @throws Exception
	 */
	public String login() throws Exception {
		IDeviceProcess process = (IDeviceProcess) ProcessFactory
				.get(Device.class);
		if (login_no == null || login_no.length() <= 0 || login_pwd == null
				|| login_pwd.length() <= 0) {
			Web.setMessage(null, "* Please input the user account and password");
			return "loginfail";
		}

		Device device = process.getUserByUserNameAndPwd(login_no, login_pwd);

		if (device == null) {
			Web.setMessage(null, "Invalid Username and/or Password!");
			return "loginfail";
		} else {
			// Set the current user to session.
			Web.getSession().setAttribute(IMDroid.CURRENT_USER, device);
		}
		
		return "loginok";
	}

	/**
	 * Log out
	 * 
	 * @return The JSF tag "logout".
	 * @throws Exception
	 */
	public String logout() throws Exception {

		return "logout";
	}
}
